package apa.wings.gwtCRUD.server.service;

import java.util.Date;


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import apa.wings.gwtCRUD.server.dao.PersonDAO;
import apa.wings.gwtCRUD.shared.dto.PersonDTO;
import apa.wings.gwtCRUD.shared.services.PersonService;

@Service("employeeService")
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDAO personDAO;

	@PostConstruct
	public void init() throws Exception {
	}

	@PreDestroy
	public void destroy() {
	}

	public PersonDTO findById(Integer id) {
		return personDAO.findById(id);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void savePerson(Integer id, String firstName, String lastName,
			Date birthDate, String sex) throws Exception {

		PersonDTO personDTO = personDAO.findById(id);

		if (personDTO == null) {
			personDTO = new PersonDTO();
			personDAO.persist(personDTO);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updatePerson(Integer id, String firstName, String lastName,
			Date birthDate, String sex) throws Exception {

		PersonDTO personDTO = personDAO.findById(id);

		if (personDTO != null) {
			personDTO.setFirstName(firstName);
			personDTO.setLastName(lastName);
			personDTO.setBirthDate(birthDate);
			personDTO.setSex(sex);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void saveOrUpdatePerson(Integer id, String firstName,
			String lastName, Date birthDate, String sex) throws Exception {

		PersonDTO personDTO = new PersonDTO(id, firstName, lastName, birthDate,
				sex);
		personDAO.merge(personDTO);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void deletePerson(Integer id) throws Exception {

		PersonDTO personDTO = personDAO.findById(id);

		if (personDTO != null)
			personDAO.remove(personDTO);

	}
}